Ext.define('WebMeV.controller.Login', {
    extend : 'Ext.app.Controller',

    //define the views
    views : ['StartLoginForm'],

    //special method that is called when your application boots
    init : function() {
             
        //control function makes it easy to listen to events on
        //your view classes and take some action with a handler function
        this.control({
                  
            //when the viewport is rendered
            'viewport > panel' : {
                render : this.onPanelRendered
            },
            
            //when you click Submit button
            'startloginform button[action=login]' : {
                click : this.onLoginRequest  
            },

            'textfield': {
                specialkey: function(field, e) {
                    if(e.getKey() == e.ENTER) {
                        var form = field.up('form').getForm();
                        if(form.isValid()){
                            Ext.Ajax.request({
                                url : 'login',
                                method:'POST',
                                params : {
                                    loginData: Ext.encode(form.getValues())
                                },
                                scope : this,
                                success : this.onLoginSuccess,
                                failure : this.onLoginFailure
                            });
                        }
                    }
                } 
            }
        });
    },

    onPanelRendered : function() {
        
    },
          
    onLoginRequest : function(button) {                    
        var form = button.up('form').getForm();
        if(form.isValid()){
            Ext.Ajax.request({
                url : 'login',
                method:'POST',
                params : {
                    loginData: Ext.encode(form.getValues())
                },
                scope : this,
                success : this.onLoginSuccess,
                failure : this.onLoginFailure
            });
        }
    },
          
    onLoginFailure : function(err) {
        //Alert the user about communication error
        Ext.MessageBox.alert('Error occured during Login', 'Please try again!');
    },

    onLoginSuccess : function(response, opts) {
        //Received response from the server
        response = Ext.decode(response.responseText);
        if(response.success){
            Ext.MessageBox.alert('Login success', response.message);
        }else 
            Ext.MessageBox.alert('Login failed', response.message);
        
    }
});

